#include "core.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>

// 创建图像
Image* image_create(uint32_t width, uint32_t height, uint8_t channels) {
    if (width == 0 || height == 0 || channels == 0) return NULL;
    
    Image* img = (Image*)malloc(sizeof(Image));
    if (!img) return NULL;
    
    img->width = width;
    img->height = height;
    img->channels = channels;
    
    size_t data_size = width * height * channels;
    img->data = (uint8_t*)aligned_alloc(data_size);
    if (!img->data) {
        free(img);
        return NULL;
    }
    
    memset(img->data, 0, data_size);
    return img;
}

// 释放图像
void image_free(Image* img) {
    if (img) {
        if (img->data) aligned_free(img->data);
        free(img);
    }
}

// 通用灰度转换
ErrorCode image_grayscale_generic(const Image* src, Image** dest) {
    if (!src) return ERR_NULL_PTR;
    if (src->channels != 3) return ERR_INVALID_CHANNELS;
    
    Image* gray = image_create(src->width, src->height, 1);
    if (!gray) return ERR_MEMORY_ALLOC;
    
    const uint8_t* src_ptr = src->data;
    uint8_t* dst_ptr = gray->data;
    const size_t num_pixels = src->width * src->height;
    
    for (size_t i = 0; i < num_pixels; i++) {
        uint8_t r = *src_ptr++;
        uint8_t g = *src_ptr++;
        uint8_t b = *src_ptr++;
        
        // Y = 0.299R + 0.587G + 0.114B
        *dst_ptr++ = (uint8_t)(0.299*r + 0.587*g + 0.114*b);
    }
    
    *dest = gray;
    return SUCCESS;
}